import CryptoJS from 'crypto-js';
//iv  偏移量
const iv = '5ofnrtcvjkxn17vw';

/**
 * 加密
 * @returns {string}
 * @param data  加密数据
 */
export function encrypt(data) {
	data = JSON.stringify(data);
	let key =  uni.getStorageSync('secret');
	if (key === '' || key == null) {
		key = '2ki9n1fdku022t6g';
	}
	const mKey = CryptoJS.enc.Utf8.parse(key);
	const mIv = CryptoJS.enc.Utf8.parse(iv);
	let encrypted = CryptoJS.AES.encrypt(data, mKey, {
		iv: mIv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding,
	});
	encrypted = encrypted.toString(); //返回的是base64格式的密文
	return encrypted;
}

/**
 * 解密
 * @param data 待解密字符串
 * @returns {string}
 */
export function decrypt(data) {
	// 获取用户key 如果不存在  使用默认key
	let key =  uni.getStorageSync('secret');
	if(key == null||key === ''){
		key = '2ki9n1fdku022t6g'
	}
	const m_key = CryptoJS.enc.Utf8.parse(key);
	const m_iv = CryptoJS.enc.Utf8.parse(iv);
	// data = CryptoJS.enc.Base64.parse(data);
	let decrypted = CryptoJS.AES.decrypt(data, m_key, {
		iv: m_iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	});
	return decrypted.toString(CryptoJS.enc.Utf8);
}